package com.excel.manager.excel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;

import com.excel.manager.annotation.Columns;

/**
 * @author ravi
 * */
public class BeanToExcel<T> {

    private Map<String, Field> fieldMapping = new HashMap<String, Field>();

    public void mapBeanToExcel(Set<T> listBeans, Class<T> clazz, String excelFile) throws ClassNotFoundException, IllegalArgumentException,
            IllegalAccessException, IOException {

        Field[] fields = clazz.getFields();
        List<String> header = new ArrayList<String>();

        for (Field field : fields) {
            Columns column = field.getAnnotation(Columns.class);
            if (column == null || column.value() == null || column.value().trim().equals("")) {
                continue;
            }
            header.add(column.value());
            fieldMapping.put(column.value(), field);
        }

        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        Sheet sheet = hssfWorkbook.createSheet();

        int counter = 0;
        Map<Integer, Object[]> rowMap = new HashMap<Integer, Object[]>();
        rowMap.put(counter++, header.toArray(new Object[header.size()]));

        for (T t : listBeans) {
            Object[] rowData = new Object[header.size()];
            for (Map.Entry<String, Field> entry : fieldMapping.entrySet()) {
                rowData[header.indexOf(entry.getKey())] = entry.getValue().get(t);
            }
            rowMap.put(counter++, rowData);
        }

        Utilities.insertRow(sheet, rowMap);

        FileOutputStream outStream = new FileOutputStream(new File(excelFile));
        hssfWorkbook.write(outStream);
        outStream.close();
    }
}
